/*
 * Copyright © 2017 eqxiu.com 北京中网易企秀科技有限公司  All rights reserved.
 */

package cn.hermit.nio.http.server.builtin;

import cn.hermit.nio.http.server.HttpResponse;
import com.sun.net.httpserver.HttpExchange;

import java.io.IOException;
import java.io.OutputStream;

/**
 * @author JackGao 高建国
 * @description //TODO 设计说明
 * @date 2/6/2017
 */
public class JavaHttpResponse extends HttpResponse {

    private HttpExchange httpExchange;

    public JavaHttpResponse(HttpExchange httpExchange) {
        this.httpExchange = httpExchange;
    }

    public void flush() {
        for (String name : header.keySet()) {
            Object val = header.get(name);
            if (val == null) continue;
            httpExchange.getResponseHeaders().set(name, val.toString());
        }
        try {
            if (body != null) {
                httpExchange.sendResponseHeaders(statusCode, body.length);
            } else {
                httpExchange.sendResponseHeaders(statusCode, 0);
            }
            OutputStream os = null;
            try {
                os = httpExchange.getResponseBody();
                os.write(body);
            } finally {
                if (os != null) {
                    os.close();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
